<template lang="pug">
  .CreateAccountModal
    Modal(
      v-model="isShowCreateModal"
      :title="createModalTitle"
      class-name="vertical-center-modal"
      width="700"
    )
      Form.ivu-row.has-rules-item2.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="130")
        FormItem.form-item.ivu-col(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'input'")
            Input(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" clearable @on-blur="(event, type) => listenCall(item.fn, item.model, event)")
            Input(v-else v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" clearable)
          template(v-if="item.type === 'select'")
            Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
            Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" :type="item.mode ? item.mode : 'date'" :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
          template(v-if="item.type === 'switch'")
            i-switch(v-model="formData[item.model]")
      
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="modalKey != 'lookModal'" type="primary" @click="handleSubmit" :loading="!isCanSubmit") 保存
</template>

<script>
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { FinanceApi } from '@/api/Finance.api.js'
import { FinanceReceivableClaimApi } from '@/api/FinanceReceivableClaim.api.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import { EmployeesApi } from '@/api/Employees.api.js'
import { setTimeout } from 'timers';

export default {
  name: 'CreateModal',

  watch: {
  },

  computed: {
    setFormItem () {
      if (this.modalKey == 'lookModal') {
        this.formItemView.map(item => {item.isDisabled = true})
      } else {
        this.formItem.map(item => {
          if (['billType', 'empName', 'billAmt', 'payforAmt', 'status', 'updateName', 'dealTime'].indexOf(item.model) != -1) {
            item.isDisabled = true
          } else {
            item.isDisabled = false
          }
        })
      }
      return this.modalKey == 'lookModal'?this.formItemView:this.formItem
    }
  },

    
  data () {
    const validateTotalMax = (rule, value, callback) => {
      if (!this.formData.amt || this.formData.amt <= 0) {
        callback(new Error('请输入大于0的数字'))
      } else {
        callback()
      }
    }
    return {
      isShowCreateModal: false,
      // isCreate: true,
      modalKey: null,
      createModalTitle: null,
      isCanSubmit: true,
      parentFormData: null,
      formData: {
        receiveID: null,
        companyID: null,
        companyName:null,
        employeeId:null,
        idCardNo: null,
        empName:null,
        insuranceTypeID:null,
        insuranceType:null,
        insuranceName:null,
        treatmentID:null,
        treatmentName:null,
        insuredID:null,
        insuredNo:null,
        amt:null,
      },
      formItem: [
        { type: 'select', label: '客户名称：', placeholder: '请选择客户名称', prop: 'companyID', model: 'companyID', style: 'ivu-col-span-12', options: 'customer', fn: 'companyIDChange' },
        { type: 'select', label: '身份证号码：', placeholder: '请选择身份证号码', prop: 'idCardNo', model: 'idCardNo', style: 'ivu-col-span-12', options: 'idCardNos', fn: 'idCardNoChange' },
        { type: 'input', label: '姓名：', placeholder: '请输入姓名', prop: 'empName', model: 'empName', style: 'ivu-col-span-12', isDisabled: true },
        { type: 'select', label: '参保险种：', placeholder: '请选择参保险种', prop: 'insuranceTypeID', model: 'insuranceTypeID', style: 'ivu-col-span-12', options: 'insuranceTypeIDList', fn: 'insuranceTypeIDChange' },
        { type: 'select', label: '待遇名称：', placeholder: '请选择待遇名称', prop: 'treatmentID', model: 'treatmentID', style: 'ivu-col-span-12', options: 'treatmentIDList', fn: 'treatmentIDChange' },
        { type: 'select', label: '参保编号：', placeholder: '请选择参保编号', prop: 'insuredID', model: 'insuredID', style: 'ivu-col-span-12', options: 'insuredIDList', fn: 'insuredIDChange'},
        { type: 'input', label: '认领金额：', placeholder: '请输入认领金额', prop: 'amt', model: 'amt', style: 'ivu-col-span-12' },
        
      ],
      formItemView: [
        { type: 'input', label: '客户名称：', placeholder: '请选择客户名称', prop: 'companyName', model: 'companyName', style: 'ivu-col-span-12', options: 'customer', fn: 'companyIDChange' },
        { type: 'input', label: '身份证号码：', placeholder: '请选择身份证号码', prop: 'idCardNo', model: 'idCardNo', style: 'ivu-col-span-12', options: 'idCardNos', fn: 'idCardNoChange' },
        { type: 'input', label: '姓名：', placeholder: '请输入姓名', prop: 'empName', model: 'empName', style: 'ivu-col-span-12', isDisabled: true },
        { type: 'input', label: '参保险种：', placeholder: '请选择参保险种', prop: 'insuranceName', model: 'insuranceName', style: 'ivu-col-span-12', options: 'insuranceTypeIDList', fn: 'insuranceTypeIDChange' },
        { type: 'input', label: '待遇名称：', placeholder: '请选择待遇名称', prop: 'treatmentName', model: 'treatmentName', style: 'ivu-col-span-12', options: 'treatmentIDList', fn: 'treatmentIDChange' },
        { type: 'input', label: '参保编号：', placeholder: '请选择参保编号', prop: 'insuredNo', model: 'insuredNo', style: 'ivu-col-span-12', options: 'insuredIDList', fn: 'insuredIDChange'},
        { type: 'input', label: '认领金额：', placeholder: '请输入认领金额', prop: 'amt', model: 'amt', style: 'ivu-col-span-12' },
        
      ],
      rules: {
        companyID: [
          { required: true, message: '请选择客户名称', trigger: 'change' }
        ],
        idCardNo: [
          { required: true, message: '请选择身份证号码', trigger: 'change' }
        ],
        empName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        insuranceTypeID: [
          { required: true, message: '请选择参保险种', trigger: 'change' }
        ],
        treatmentID: [
          { required: true, message: '请选择待遇名称', trigger: 'change' }
        ],
        insuredID: [
          { required: true, message: '请选择参保编号', trigger: 'change' }
        ],
        amt: [
          { required: true, message: '请输入认领金额(不能为0/负数)', trigger: 'blur', validator: validateTotalMax }
        ]
      },
      arrListDown: {
        options: [],
        customer: [],
        insuranceTypeIDList:[],
        idCardNos: [],
        treatmentIDList:[],
        insuredIDList:[],
      },
      // selectedParentCompany: {}, // 选中的集团
    }
  },

  mounted () {
    // this.companys()
    // this.getParentCompanys()
    this.getInsuranceTypeList()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },
    
    // 获取公司
    async companys () {
      var params = {
        PageIndex: 1,
        PageSize: 10000,
        Args: ''
      }
      Common.companys(params, this.arrListDown, 'customer')
    },    

    getLabel(list,key){
      for(let item of list) {
        if(item.value == key) {
          return item.label
        }
      }
    },

    // 获取认领的公司下拉框-0
    async receivableCompanys (matchGuid,matchRemark) {
      var params = {
        matchGuid: matchGuid,
        matchRemark: matchRemark
      }
      let res = await FinanceReceivableClaimApi.companys(params)
      console.log('获取认领的公司下拉框 res: ', res)
      if (res.status === 200) {
        var customerObj = res.data.find(item => {return item.group == 'customer'})
        var customerArr = []
        customerObj.items.map(item => {
          customerArr.push({value: item.key, label: item.value})
        })
        this.arrListDown.customer = customerArr
      } else {
        this.tableData = []
      }
    },

    // 客户名称改变-1
    async companyIDChange (model, value) {
      if(!value){
        return
      }
      this.formData.idCardNo = null
      this.formData.empName = null
      this.formData.employeeId = null
      this.formData.insuredID = null
      this.insuredIDListChange()
      this.formData.companyName = this.getLabel(this.arrListDown.customer, value)
      console.log(this.formData)
      var params = {
        companyID: value
      }
      let res = await FinanceReceivableClaimApi.getEmployeeList(params)
      console.log('获取公司职员 res: ', res)
      if (res.status === 200) {
        // var customerObj = res.data.find(item => {return item.group == 'customer'})
        var idCardNos = []
        res.data.data.map(item => {
          idCardNos.push({value: item.value, label: item.text,})
        })
        this.arrListDown.idCardNos = idCardNos
      } else {
      }
    },

    

    // 身份证改变-2
    async idCardNoChange (model, value) {
      let res = await EmployeesApi.getEmployee({id: value})
      console.log(res,'getemployee')
      if (res.status === 200 && res.data.success) {
        this.formData.empName = res.data.data.name ? res.data.data.name + '' : ''
        this.formData.employeeId = res.data.data.id ? res.data.data.id + '' : ''
      } else {
         this.formData.empName = ''
        this.formData.employeeId = ''
      }
      this.formData.insuredID = ''
      this.insuredIDListChange()
    },

    // 获取参保险种-0
    async getInsuranceTypeList () {
      let res = await TreatmentBasicsTypeApi.getInsuranceTypeList()
      console.log('获取enum下拉框 res: ', res)
      if (res.status === 200) {
        var insuranceTypeIDObj = res.data.data
        var insuranceTypeIDList = []
        insuranceTypeIDObj.map(item => {
          insuranceTypeIDList.push({value: item.value, label: item.text})
        })
        this.arrListDown.insuranceTypeIDList = insuranceTypeIDList
      } else {
        this.arrListDown.insuranceTypeIDList = []
      }
    },

    // 参保险种-1
    async insuranceTypeIDChange (model, value) {
      this.formData.insuranceType = this.getLabel(this.arrListDown.insuranceTypeIDList, value)
      let res = await TreatmentBasicsTypeApi.getBasicsTypeList({insuredTypeId: value})
      console.log(res,'enum')
      if (res.status === 200) {
        var treatmentIDObj = res.data.data
        var treatmentIDList = []
        treatmentIDObj.map(item => {
          treatmentIDList.push({value: item.value, label: item.text})
        })
        this.arrListDown.treatmentIDList = treatmentIDList
      } else {
        this.arrListDown.treatmentIDList = []
      }
      this.formData.insuredID = ''
      this.insuredIDListChange()
    },
    // 获取参保编号
    async insuredIDListChange () {
      console.log('insuredIDListChange',this.formData.InsuranceType == null || this.formData.employeeId == null)
      if(this.formData.insuranceTypeID == null || this.formData.employeeId == null) {
        this.arrListDown.insuredIDList = []
        return
      }
      let res = await TreatmentBasicsTypeApi.getEmployeeConfigList({type: this.formData.InsuranceType == '商保' ? 3 : this.formData.InsuranceType == '公积金' ? 2 : 1, employeeGUID:this.formData.employeeId})
      console.log(res,'insuredIDListChange')
      if (res.status === 200) {
        var insuredIDObj = res.data.data
        var insuredIDList = []
        insuredIDObj.map(item => {
          insuredIDList.push({value: item.value, label: item.text})
        })
        this.arrListDown.insuredIDList = insuredIDList
      } else {
        this.arrListDown.insuredIDList = []
      }
    },

    // 待遇名称-2
    async treatmentIDChange (model, value) {
      console.log(this.formData,'this.formData',this.formData.treatmentId)
      this.formData.treatmentName = this.getLabel(this.arrListDown.treatmentIDList, value)
    },

    async insuredIDChange (model, value) {
      console.log(this.formData,'this.formData',this.formData.insuredID)
      this.formData.insuredNo = this.getLabel(this.arrListDown.insuredIDList, value)
    },
    

    cancel () {
      this.isShowCreateModal = false
    },

    show (parentFormData) {
      console.log('⭐ parentFormData: ', parentFormData)
      console.log('⭐ model: ', this.modalKey)
      console.log('⭐ formdata: ', this.formData)
      this.isCanSubmit = true
      this.isShowCreateModal = true
      this.formData.companyID = null
      this.$refs.formData.resetFields({})
      this.parentFormData = parentFormData
      this.formData.receiveID = parentFormData.receiveID
    },

    // 提交表单
    handleSubmit () {
      console.log('this.formData: ', this.formData)
      console.log('this.parentFormData: ', this.parentFormData)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          var selectedCompany = this.arrListDown.customer.find(item => {return item.value == this.formData.companyID})
          console.log('selectedCompany: ', selectedCompany)
          this.formData.companyName = selectedCompany.label
          let idCardNo = this.getLabel(this.arrListDown.idCardNos, this.formData.idCardNo)
          
          FinanceReceivableClaimApi.addTreatmentClaim({ ...this.formData, idCardNo:idCardNo}).then(resp=>{
            if (resp.data.success) {
              this.$Message.success(resp.data.message)
              this.isShowCreateModal = false
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              this.$Message.warning(resp.data.message)
            }
          })
        } else {
          this.isCanSubmit = true
          this.$Message.warning('输入有误，请返回检查!')
        }
      })
    },

    // 根据ID获取信息
    async getModel (id) {
      let resp = await FinanceReceivableClaimApi.getTreatmentView ({id: id})
      if (resp.status === 200 && resp.data.success) {
        this.isShowCreateModal = true
        var result = resp.data.data
        // 相应赋值
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = result[key] + ''
        })
        console.log('❤ this.formData: ', this.formData)
      } else {
        this.$Message.error({
          content: resp.data.message,
          duration: 10,
          closable: true
        })
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
